package com.fishingwithme.android.ui.viewmodels

import android.util.Log
import androidx.paging.PagingSource
import androidx.paging.PagingState
import com.fishingwithme.android.data.model.PointsRecord
import com.fishingwithme.android.data.repository.FishingRepository
import kotlinx.coroutines.flow.firstOrNull

class CreditRecordsPagingSource(
    private val repository: FishingRepository
) : PagingSource<Int, PointsRecord>() {

    override fun getRefreshKey(state: PagingState<Int, PointsRecord>): Int? {
        return state.anchorPosition?.let { anchorPosition ->
            state.closestPageToPosition(anchorPosition)?.prevKey?.plus(1)
                ?: state.closestPageToPosition(anchorPosition)?.nextKey?.minus(1)
        }
    }

    override suspend fun load(params: LoadParams<Int>): LoadResult<Int, PointsRecord> {
        val page = params.key ?: 1
        return try {
            Log.d("CreditRecords", "Loading page $page with page size ${params.loadSize}")
            val response = repository.getCreditRecords(page, params.loadSize).firstOrNull()
            response?.fold(
                onSuccess = { pageResponse ->
                    Log.d("CreditRecords", "Received response with ${pageResponse.records?.size ?: 0} records")
                    val data = pageResponse.records ?: emptyList()
                    val prevKey = if (page == 1) null else page - 1
                    // Fix nextKey calculation: check if we have more records based on total
                    val nextKey = if (pageResponse.total != null && 
                                      pageResponse.current != null && 
                                      pageResponse.size != null &&
                                      pageResponse.current * pageResponse.size < pageResponse.total) {
                        page + 1
                    } else {
                        null
                    }
                    Log.d("CreditRecords", "Calculated keys - prevKey: $prevKey, nextKey: $nextKey")
                    LoadResult.Page(
                        data = data,
                        prevKey = prevKey,
                        nextKey = nextKey
                    )
                },
                onFailure = { throwable ->
                    Log.e("CreditRecords", "Failed to load credit records", throwable)
                    LoadResult.Error(throwable)
                }
            )?: LoadResult.Error(Exception("No data received"))
        } catch (e: Exception) {
            Log.e("CreditRecords", "Exception while loading credit records", e)
            LoadResult.Error(e)
        }
    }
}